from pymongo import MongoClient, ASCENDING
from Utils.DataUtil import list_dir
# from Utils.DateTimeUtil import dateformatchange
import pandas as pd
from datetime import datetime, timedelta, date
import numpy as np

class MongoDBClient(object):
    # 饿汉式 单例模式
    def __new__(cls):
        if not hasattr(cls, 'instance'):
            cls.instance = super(MongoDBClient, cls).__new__(cls)
        return cls.instance
    # 代理ip Redis 连接池
    def __init__(self):
        self.mgdb = MongoClient(host='127.0.0.1', connect=False, maxPoolSize=2000)

    def getMongoClient(self):
        return self.mgdb

# mc = MongoClient(host='192.168.50.188', port=27017)  # Mongo连接
myMongo = MongoDBClient().getMongoClient()
dbSecurities = myMongo['jq_securities']


def getTradeDays(start_date, end_date=None) -> np.ndarray:
    cl = dbSecurities['trade_days']  # 指定要操作的集合
    if isinstance(start_date, str):
        st = datetime.strptime(start_date, '%Y-%m-%d')
    elif isinstance(start_date, date):
        st = datetime.combine(start_date, datetime.min.time())

    if end_date is None:
        cursor = cl.find({"trade_days": {"$gte": st}}, {"trade_days": 1, "_id": 0})
    else:
        if isinstance(end_date, str):
            et = datetime.strptime(end_date, '%Y-%m-%d')
        elif isinstance(end_date, date):
            et = datetime.combine(end_date, datetime.min.time())

        cursor = cl.find({"trade_days": {"$lte": et, "$gte": st}}, {"trade_days": 1, "_id": 0})

    l = list(cursor)
    df = pd.DataFrame(l)

    if df.empty:
        print('股票估值数据读取失败，程序中止')
    df = df.drop_duplicates()

    def f(x): #将Timestamp对象转换为原生Python datetime对象
        return x.to_pydatetime().date()

    df['trade_days'] = df['trade_days'].apply(f)

    return df['trade_days'].values

# count<0时目前最多取101个，>0暂时没发现有限制
def getTradeDaysWithCount(end_date, count: int) -> np.ndarray:
    cl = dbSecurities['trade_days']  # 指定要操作的集合
    if isinstance(end_date, str):
        end_date = datetime.strptime(end_date, '%Y-%m-%d')
    elif isinstance(end_date, date):
        end_date = datetime.combine(end_date, datetime.min.time())

    if count > 0: # 往后取
        cursor = cl.find({"trade_days": {"$gte": end_date}}, {"trade_days": 1, "_id": 0}).sort('trade_days', 1).limit(count)
    if count < 0: # 往前取
        cursor = cl.find({"trade_days": {"$lte": end_date}}, {"trade_days": 1, "_id": 0}).sort('trade_days', -1).limit(-count)
    l = list(cursor)
    df = pd.DataFrame(l)
    df = df.drop_duplicates()

    def f(x):
        return x.to_pydatetime().date()
    df['trade_days'] = df['trade_days'].apply(f)
    return df['trade_days'].values


def getAllTradeDays() -> np.ndarray:
    cl = dbSecurities['trade_days']  # 指定要操作的集合
    cursor = cl.find()

    l = list(cursor)
    df = pd.DataFrame(l)

    if df.empty:
        print('交易日历数据读取失败，程序中止')
        return

    df = df.drop_duplicates()
    df = df.drop('_id', axis=1)

    def f(x):
        return x.to_pydatetime().date()

    df['trade_days'] = df['trade_days'].apply(f)

    return df['trade_days'].values


if __name__ == '__main__':
#     print(getTradeDaysWithCount('2010-01-01', 2))
    # insertTradedays()
    # nar = getTradeDays('2018-06-01', '2018-08-08')
    # print(getAllTradeDays())
    # nar = getTradeDaysWithCount('2019-01-08', 20)[0]
    nar = getTradeDaysWithCount('2019-01-07', -125)
    print(nar)
    # d0 = datetime.fromtimestamp(l[0]).strftime('%Y-%m-%d')
    # print(ticks_to_datetime(l[0]))
